<template>
  <a-modal v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false" draggable
    :width="width >= 600 ? 600 : '100%'" @before-ok="save" @close="reset">
    <GiForm ref="formRef" v-model="form" :options="options" :columns="columns" />
  </a-modal>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { useResetReactive } from '@/hooks'
import { useDict, useNickname, useTaskName, useLocName, useTestName } from '@/hooks/app'
import { addTestLog, getTestLog, updateTestLog } from '@/apis/task/testLog'
import { type Columns, GiForm, type Options } from '@/components/GiForm'
import { ref, computed, reactive, watch } from 'vue'
const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const dataId = ref('')
const visible = ref(false)
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改试验工作量' : '新增试验工作量'))
const formRef = ref<InstanceType<typeof GiForm>>()
const { register_type, fault_status } = useDict('register_type', 'fault_status')


const { nicknameList, getNicknameList } = useNickname()

const { taskNameList, getTaskNameList } = useTaskName()

const { locNameList, getLocNameList } = useLocName()

const { testNameList, getTestNameList } = useTestName()

const options: Options = {
  form: { size: 'large' },
  btns: { hide: true },
}

const [form, resetForm] = useResetReactive({
  logUserIds: [],
  startTime: '',
  endTime: '',
  testHour: 0,
  overtimeHour: 0,
  registerStatus: '',
  isFault: '',
  faultDescription: '',
  name: '',
  testDescription: '',
  taskId: ''
})

const columns: Columns = reactive([
  {
    label: '试验人员',
    field: 'logUserIds',
    type: 'select',
    options: nicknameList,
    props: {
      multiple: true,
      allowClear: true,
      allowSearch: true,
    },
    rules: [{ required: true, message: '请选择试验人员' }]
  },
  {
    label: '开始时间',
    field: 'startTime',
    type: 'date-picker',
    props: {
      showTime: true,
    },
    rules: [{ required: true, message: '请输入开始时间' }]
  },
  {
    label: '结束时间',
    field: 'endTime',
    type: 'date-picker',
    props: {
      showTime: true,
    },
    rules: [{ required: true, message: '请输入结束时间' }]
  },
  {
    label: '试验时数',
    field: 'testHour',
    type: 'input-number',
    props: {
      disabled: true
    },
    rules: [{ required: true, message: '试验时数将自动计算' }]
  },
  {
    label: '加班时数',
    field: 'overtimeHour',
    type: 'input-number',
    props: {
      disabled: true
    },
    rules: [{ required: true, message: '加班时数将自动计算' }]
  },
  {
    label: '登记项目',
    field: 'registerStatus',
    type: 'select',
    options: register_type,
    rules: [{ required: true, message: '请输入登记项目' }]
  },
  {
    label: '发动机是否故障',
    field: 'isFault',
    type: 'radio-group',
    options: fault_status,
    rules: [{ required: true, message: '请输入发动机是否故障' }]
  },
  {
    label: '故障描述',
    field: 'faultDescription',
    type: 'textarea',
    rules: [{ required: true, message: '请输入故障描述' }]
  },
  {
    label: '试验名称',
    field: 'testId',
    type: 'select',
    options: testNameList,
    props: {
      allowSearch: true,
    },
    rules: [{ required: true, message: '请输入试验名称' }]
  },
  {
    label: '试验情况描述',
    field: 'testDescription',
    type: 'textarea',
    rules: [{ required: true, message: '请输入试验情况描述' }]
  },
  {
    label: '任务名称',
    field: 'taskId',
    type: 'select',
    options: taskNameList,
    props: {
      allowSearch: true,
    },
    rules: [{ required: true, message: '请输入任务名称' }]
  },
  {
    label: '设备地点',
    field: 'locId',
    type: 'select',
    options: locNameList,
    props: {
      allowSearch: true,
    },
    rules: [{ required: true, message: '请输入设备地点' }]
  },
])

// 计算试验时数和加班时数
const calculateHours = () => {
  if (!form.startTime || !form.endTime) return
  
  const startTime = new Date(form.startTime)
  const endTime = new Date(form.endTime)
  
  // 检查结束时间是否早于开始时间
  if (endTime <= startTime) {
    Message.warning('结束时间必须晚于开始时间')
    return
  }
  
  // 计算总试验时数（小时）
  const totalHours = (endTime.getTime() - startTime.getTime()) / (1000 * 60 * 60)
  form.testHour = Math.round(totalHours * 100) / 100 // 保留两位小数
  
  // 计算加班时数
  let normalWorkHours = 0
  let currentTime = new Date(startTime)
  
  // 遍历每一天计算正常工作时间
  while (currentTime < endTime) {
    const dayStart = new Date(currentTime)
    dayStart.setHours(0, 0, 0, 0)
    
    const dayEnd = new Date(dayStart)
    dayEnd.setDate(dayEnd.getDate() + 1)
    dayEnd.setHours(0, 0, 0, 0)
    
    // 上午工作时间：9:00-12:00
    const morningStart = new Date(dayStart)
    morningStart.setHours(9, 0, 0, 0)
    
    const morningEnd = new Date(dayStart)
    morningEnd.setHours(12, 0, 0, 0)
    
    // 下午工作时间：14:00-17:00
    const afternoonStart = new Date(dayStart)
    afternoonStart.setHours(14, 0, 0, 0)
    
    const afternoonEnd = new Date(dayStart)
    afternoonEnd.setHours(17, 0, 0, 0)
    
    // 计算当天上午的正常工作时间重叠
    const actualMorningStart = currentTime > morningStart ? currentTime : morningStart
    const actualMorningEnd = dayEnd < morningEnd ? dayEnd : morningEnd
    const actualEnd = dayEnd < endTime ? dayEnd : endTime
    
    if (actualMorningStart < actualMorningEnd && actualMorningStart < actualEnd) {
      const minEnd = actualMorningEnd < actualEnd ? actualMorningEnd : actualEnd
      const morningOverlap = Math.max(0, minEnd.getTime() - actualMorningStart.getTime()) / (1000 * 60 * 60)
      normalWorkHours += morningOverlap
    }
    
    // 计算当天下午的正常工作时间重叠
    const actualAfternoonStart = currentTime > afternoonStart ? currentTime : afternoonStart
    const actualAfternoonEnd = dayEnd < afternoonEnd ? dayEnd : afternoonEnd
    
    if (actualAfternoonStart < actualAfternoonEnd && actualAfternoonStart < actualEnd) {
      const minEnd = actualAfternoonEnd < actualEnd ? actualAfternoonEnd : actualEnd
      const afternoonOverlap = Math.max(0, minEnd.getTime() - actualAfternoonStart.getTime()) / (1000 * 60 * 60)
      normalWorkHours += afternoonOverlap
    }
    
    // 移动到下一天
    currentTime = dayEnd
  }
  
  // 加班时数 = 总时数 - 正常工作时间
  const overtime = Math.max(0, totalHours - normalWorkHours)
  form.overtimeHour = Math.round(overtime * 100) / 100 // 保留两位小数
}

// 监听开始时间和结束时间变化，自动计算时数
watch(
  () => [form.startTime, form.endTime],
  () => {
    calculateHours()
  },
  { deep: true }
)

// 重置
const reset = async () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
  if (!nicknameList.value.length) {
    await getNicknameList()
  }
  if (!taskNameList.value.length) {
    await getTaskNameList()
  }
  if (!locNameList.value.length) {
    await getLocNameList()
  }
  if (!testNameList.value.length) {
    await getTestNameList()
  }
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false
    if (isUpdate.value) {
      await updateTestLog(form, dataId.value)
      Message.success('修改成功')
    } else {
      await addTestLog(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

// 新增
const onAdd = async () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  const { data } = await getTestLog(id)
  Object.assign(form, data)
  visible.value = true
}

defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss"></style>
